<template>
    <el-container class="app-container">
        <el-main>
            <KkGrid v-bind="gridBind">
                <template v-slot:createdAtSlot="scope">
                    {{ parseTime(scope.row.createdAt) }}
                </template>
                <template v-slot:actionsSlot="scope">
                    <el-button type="text" icon="Plus" size="small" @click="handleAdd(scope.row)"
                        style="padding: 1px;margin-left: 5px;">
                        新增
                    </el-button>
                    <el-button type="text" icon="Edit" size="small" @click="handleUpdate(scope.row)"
                        style="padding: 1px;margin-left: 5px;">
                        修改
                    </el-button>
                    <el-button type="text" icon="Delete" size="small" @click="handleDelete(scope.row)"
                        style="padding: 1px;margin-left: 5px;">
                        删除
                    </el-button>
                </template>
            </KkGrid>
        </el-main>

        <!-- 添加或修改菜单对话框 -->
        <el-drawer :title="title" v-model="detailDialogVisible" :size="800" append-to-body>
            <el-form ref="menuFormRef" :model="columnFormData" :rules="columnFormRules" label-width="100px"
                label-suffix=":">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级栏目" prop="parentId">
                            <el-tree-select v-model="columnFormData.parentId" :data="columnOptions"
                                :check-strictly="true" :render-after-expand="false" placeholder="选择上级栏目" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="栏目名称" prop="name">
                            <el-input v-model="columnFormData.name" placeholder="请输入栏目名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="描述" prop="description">
                            <el-input type="textarea" :rows="{ minRows: 2 }" v-model="columnFormData.description"
                                placeholder="请输入描述" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="显示排序" prop="orderNum">
                            <el-input-number v-model="columnFormData.orderNum" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancelForm">取 消</el-button>
            </div>
        </el-drawer>
    </el-container>
</template>

<script>
import cmsColumnApi from '@/api/cmsColumnApi';
export default {
    data() {
        return {
            columnOptions: [],
            gridBind: {
                loading: false,
                size: 'small',
                data: [],
                columns: [
                    { label: '栏目名称', prop: 'name', width: '160', showOverflowTooltip: true },
                    { label: '排序', prop: 'orderNum', width: '60' },
                    { label: '描述', prop: 'description', },
                    { label: '创建时间', prop: 'createAt', width: '180', align: 'center', slot: 'createdAtSlot' },
                    { label: '操作', prop: 'actions', width: '320', align: 'center', slot: 'actionsSlot' },
                ],
                treeConfig: {
                    rowKey: 'id',
                    treeProps: {
                        children: 'children',
                        hasChildren: 'hasChildren'
                    }
                },
                toolbarConfig: {
                    visible: true,
                    create: true,
                    delete: false,
                    refresh: true,
                    custom: true,
                    buttons: [],
                    tools: [],
                },
            },
            columnFormData: {
                id: null,
                parentId: 0,
                name: '',
                orderNum: 0,
                description: ''
            },
            columnFormRules: {
                name: [
                    { required: true, message: '请输入栏目名称', trigger: 'blur' }
                ],
            },
            detailDialogVisible: false,
            title: ''
        }
    },
    mounted() {
        // 初始化菜单列表
        this.getList();
    },
    methods: {
        getList() {
            this.gridBind.loading = true;
            cmsColumnApi.listTree().then((response) => {
                this.gridBind.data = response.data;

                this.columnOptions = response.data.map(column => ({
                    id: column.id,
                    label: column.name,
                    value: column.id,
                    children: column.children ? column.children.map(child => ({
                        id: child.id,
                        label: child.name,
                        value: child.id
                    })) : []
                }));
            }).catch((error) => {
                console.error("Error fetching menu list:", error);
            }).finally(() => {
                this.gridBind.loading = false;
            });
        },
        handleRefresh() {
            this.getList();
        },
        handleAdd(row) {
            this.detailDialogVisible = true;
            this.title = row ? '新增子栏目' : '新增栏目';
            this.columnFormData = {
                id: null,
                parentId: row ? row.id : 0,
                name: '',
                description: '',
                orderNum: 0,

            };
        },
        handleUpdate(row) {
            this.detailDialogVisible = true;
            this.title = '修改栏目';
            this.columnFormData = { ...row };
        },
        submitForm() {
            this.$refs.menuFormRef.validate((valid) => {
                if (!valid) {
                    console.error("Form validation failed");
                    return;
                }
                if (this.columnFormData.id) {
                    cmsColumnApi.update(this.columnFormData)
                        .then(() => {
                            this.detailDialogVisible = false;
                            this.getList();
                        })
                        .catch((error) => {
                            console.error("Error updating menu:", error);
                        })
                        .finally(() => {
                        });
                    return;
                } else {
                    cmsColumnApi.create(this.columnFormData)
                        .then(() => {
                            this.detailDialogVisible = false;
                            this.getList();
                        })
                        .catch((error) => {
                            console.error("Error saving menu:", error);
                        })
                        .finally(() => {
                        });
                }
            });
        },
        cancelForm() {
            this.detailDialogVisible = false;
            this.columnFormData = {
                id: null,
                parentId: 0,
                name: '',
                description: '',
                orderNum: 0,
            };
        },
        handleDelete(row) {
            this.$confirm('确定删除该栏目吗？', '警告', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                cmsColumnApi.delete(row.id).then(() => {
                    this.$message.success('栏目删除成功');
                    this.getList();
                });
            }).catch(() => { });
        },
        parseTime(time) {
            if (!time) return '-';
            const date = new Date(time);
            return date.toLocaleString();
        },
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    background-color: #ffffff;
}
</style>
